package com.xyd.servlet;

import com.xyd.entity.User;
import com.xyd.service.OrderService;
import com.xyd.service.impl.OrderServiceImpl;
import com.xyd.util.CookieUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：清空购物车
 *
 * @author 张吉哲
 * @date 2021/1/15 11:13
 */
@WebServlet("/cartBuyServlet")
public class CartBuyServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    User user = (User) request.getSession().getAttribute("user");
    String eoCost1 = request.getParameter("eoCost");
    double eoCost = Double.parseDouble(eoCost1);
    OrderService orderService = new OrderServiceImpl();
    Long eoId = orderService
        .addOrder(user.getEuUserId(), user.getEuUsername(), user.getEuAddress(), eoCost);
    if (eoId == null) {
      response.getWriter().print("购买失败，请联系管理员");
      return;
    }
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(user.getEuUserId() + CookieUtil.getCookieName())) {
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        break;
      }
    }
    response.sendRedirect(request.getContextPath() + "/productBuyServlet?WIDout_trade_no=" + eoId
        + "&WIDtotal_amount=" + eoCost + "&WIDsubject=" + user.getEuUsername() + "的购物车");
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
